<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <div class="basic-container">
          <div class="top">
            <span class="title">分组信息</span>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="数据源名称">
              <a-input
                disabled
                placeholder="请输入数据源名称"
                allow-clear
                v-decorator="['dataSource_dictText']"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="配置名称">
              <a-input
                disabled
                placeholder="请输入配置名称"
                allow-clear
                v-decorator="['configId_dictText']"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="数据表">
              <a-input
                disabled
                placeholder="请输入数据表"
                allow-clear
                v-decorator="['tableName']"/>
            </a-form-item>
          </div>
          <div class="center">
            <span class="title">维度信息</span>
            <a-table
              :pagination="false"
              ref="table"
              size="middle"
              :scroll="{x:true}"
              bordered
              rowKey="name"
              :columns="columns"
              :dataSource="dataSource"
              class="j-table-force-nowrap">
              <span slot="dictName" slot-scope="dictName">
                {{ dictName }}
              </span>
               <span slot="dictType" slot-scope="dictType">
                {{ formatDictType(dictType) }}
              </span>

              <span slot="dictValue" slot-scope="dictValue, record">
                <j-dict-select-tag
                  v-if="record.dictType == '1'"
                  type="list"
                  :trigger-change="true"
                  :dictCode="record.dictCode"
                  placeholder="字典详情查看"
                 />
                 <j-dict-select-tag
                  v-if="record.dictType == '3'"
                  type="list"
                  :trigger-change="true"
                  :dictCode="record.dictTable + ',' + record.dictValue + ',' + record.dictCode"
                  placeholder="字典详情查看"
                 />
              </span>
            </a-table>
          </div>
          <div class="center">
            <span class="title">基本信息</span>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="字段名称">
              <a-input
                disabled
                placeholder="请输入字段名称"
                allow-clear
                v-decorator="['tableColumn']"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="指标名称">
              <a-input
                placeholder="请输入指标名称"
                allow-clear
                v-decorator="['name', { rules: [{ required: true, message: '请输入指标名称!', pattern: '[^ \x22]+' }] } ]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注">
              <a-textarea
                allow-clear
                placeholder="请输入备注"
                v-decorator="['remark', {'initialValue':''}]"/>
            </a-form-item>
            <a-form-item
              disabled
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="数据类型">
              <a-input
                disabled
                placeholder="请输入数据类型"
                allow-clear
                v-decorator="['dataType_dictText']"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="长度">
              <a-input-number
                disabled
                allow-clear
                v-decorator="[ 'columnLength',{'initialValue':0}]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="小数精度">
              <a-input-number
                disabled
                allow-clear
                v-decorator="[ 'scale',{'initialValue':0}]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="统计单位">
              <a-input
                placeholder="请输入字段名"
                allow-clear
                v-decorator="['unit', {} ]"/>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否率值">
              <a-radio-group v-decorator="['isPercent', { 'initialValue': 0 }]" @change="handleIsPercentChange">
                <a-radio :value="1">是</a-radio>
                <a-radio :value="0">否</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="汇聚方式">
              <j-dict-select-tag type="list" v-decorator="['groupType', { rules: [{ required: form.getFieldValue('isPercent') === 0, message: '请选择汇聚方式!' }] }]" dictCode="index_group_type" placeholder="请选择汇聚方式" :trigger-change="true" :disabled="form.getFieldValue('isPercent') === 1" />
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
              <a-radio-group v-decorator="['status', { initialValue: 1 }]">
                <a-radio :value="1">启用</a-radio>
                <a-radio :value="0">停用</a-radio>
              </a-radio-group>
            </a-form-item>
          </div>
          <div class="center" v-show="false">
            <span class="title">指标标签</span>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="指标标签">
              <a-select
                :getPopupContainer="trigger => trigger.parentNode"
                mode="multiple"
                v-decorator="['labels', {}]"
                placeholder="请选择指标标签">
                <a-select-option :value="item.id" :key="item.id" v-for="item in labelList">
                  {{ item.labelName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </div>
        </div>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>
import pick from 'lodash.pick'
import { httpAction, getAction } from '@/api/manage'

export default {
  name: 'ScSituationIndexInfoForm',
  components: {
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
    // dataSource: {
    //   type: Array,
    //   default: () => {
    //     return []
    //   }
    // }
  },
  data() {
    return {
      dictTypes: [
        { id: 1, name: '根据系统字典' },
        { id: 3, name: '自定义字典' },
        { id: 0, name: '无字典' }
      ],
      labelList: [],
      dataSource: [],
      columns: [
        {
          title: '维度名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '字典配置',
          align: 'center',
          dataIndex: 'dictType',
          scopedSlots: { customRender: 'dictType' }
        },
        {
          title: '字典详情查看',
          align: 'center',
          dataIndex: 'dictValue',
          scopedSlots: { customRender: 'dictValue' }
        }
      ],
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
      },
      url: {
        add: '/index/scSituationIndexInfo/add',
        edit: '/index/scSituationIndexInfo/edit',
        queryById: '/index/scSituationIndexInfo/queryById'
      }
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  methods: {
    formatDictType(val) {
      var dictTypeObj = this.dictTypes.find(item => item.id == val)
      if (dictTypeObj != undefined && dictTypeObj != null) {
        return dictTypeObj.name
      }
      return val
    },
    getLabelList() {
      // this.labelList = [{ id: 1, labelName: '123' }, { id: 2, labelName: '345' }]
      getAction('/index/scSituationIndexLabel/list', { pageNo: 1, pageSize: 10000 }).then((res) => {
        if (res.success) {
          this.labelList = res.result.records
        } else {
          this.labelList = []
        }
      })
    },
    resetForm() {
      this.dataSource = []
      this.form.resetFields()
    },
    add() {
      this.edit({})
    },
    edit(recordTemp) {
      var record = JSON.parse(JSON.stringify(recordTemp))
      if (record.labels == '') {
        record.labels = []
      } else {
        record.labels = record.labels.split(',')
      }
      this.getLabelList()
      var dataSourceTemp = []

      if (record.dimensionInfoVoList != null) {
        record.dimensionInfoVoList.forEach(item => {
          getAction('/dimension/scSituationDimensionType/queryById', { id: item.dimensionType }).then((res) => {
            if (res.success) {
              this.dataSource.push({
                dictType: res.result.dictType,
                dictTable: res.result.dictTable,
                dictCode: res.result.dictCode,
                dictName: res.result.dimensionName,
                dictValue: res.result.dictValue,
                dimensionType: item.dimensionType,
                name: item.name
              })
            } else {
              this.dataSource.push(item)
            }
          })
        })
      }
      // 详情
      // this.dataSource = JSON.parse(JSON.stringify(dataSourceTemp))
      console.log(this.dataSource)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'name', 'configId_dictText', 'dataSource_dictText', 'tableName', 'tableColumn', 'dataType_dictText', 'columnLength', 'scale', 'remark', 'unit', 'isPercent', 'groupType', 'status', 'labels'))
      })
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        const params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          const formData = Object.assign(this.model, values)
          formData.groupType = formData.isPercent ? undefined : formData.groupType // 根据率值选择设置汇聚方式
          if (formData.labels == null || formData.labels.length == 0) {
            formData.labels = ''
          } else {
            var labelsStr = ''
            formData.labels.forEach((item, index) => {
              if (index == 0) {
                labelsStr += item
              } else {
                labelsStr += ',' + item
              }
            })
          }
          formData.labels = labelsStr
          console.log(formData)

          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              this.resetForm()
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'name', 'configId_dictText', 'dataSource_dictText', 'tableName', 'tableColumn', 'columnLength', 'scale', 'remark', 'unit', 'isPercent', 'groupType', 'status', 'labels'))
    },
    // 是否率值项选择值变化事件响应
    handleIsPercentChange() {
      this.form.resetFields(['groupType'])
    },
  }
}
</script>

<style lang="less" scoped>
.basic-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 0 20px;
  overflow-y: auto;
  .title {
    font-size: 15px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 500;
    color: #222222;
    width: 100%;
    text-align: left;
  }
  .top {
    width: 100%;
    border-bottom: 1px solid #d9d9d9;
    padding-top: 5px;
  }
  .center {
    width: 100%;
    border-bottom: 1px solid #d9d9d9;
    padding-top: 10px;
  }
  .top,
  .center,
  .bottom {
    .item {
      width: 100%;
      height: 33px;
      margin-bottom: 15px;
      .item-left {
        width: 250px;
        float: left;
        text-align: left;
        line-height: 32px;
        font-size: 14px;
        padding-left: 70px;
        .requrid {
          color: red;
        }
      }
      .item-value {
        float: left;
        width: 620px;
        .radio-line {
          line-height: 33px;
        }
      }
      .item-error {
        float: left;
        line-height: 30px;
        margin-left: 15px;
        font-size: 15px;
        color: red;
      }
    }
    .code-item {
      width: 100%;
      height: 33px;
      .span-title {
        margin-left: 250px;
        width: 50px;
        line-height: 30px;
        display: inline-block;
        text-align: right;
      }
      .code-item-input {
        display: inline-block;
        margin-left: 0;
        width: 560px;
      }
    }
  }

  .bottom {
    width: 100%;
    height: calc(100% - 325px);
    padding-top: 5px;
    .content-box {
      width: 100%;
      height: calc(100% - 90px);
      .left,
      .btn,
      .right,
      .other {
        height: 100%;
        float: left;
      }
      .left {
        width: 500px;
        background-color: antiquewhite;
      }
      .btn {
        width: 60px;
        background-color: aqua;
      }
      .right {
        width: 350px;
        background-color: cadetblue;
      }
      .other {
        width: 350px;
        background-color: chartreuse;
      }
    }
  }
}
</style>
